package com.sgl.user.controller;

import com.sgl.user.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Random;


/**
 * Created by Administrator on 2017/7/10.
 */

@Controller
public class UserController {

    private  final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private DiscoveryClient discoveryClient;

    @RequestMapping("/")
    @ResponseBody
    public String index() throws Exception{

        int sleepTime = new Random().nextInt(3000);
        logger.info("sleepTime: {}", sleepTime);
        Thread.sleep(sleepTime);

        ServiceInstance instance = discoveryClient.getLocalServiceInstance();

        logger.info("/hello, host:{},service_id:{}", instance.getHost(),instance.getServiceId());

        return "hello !";
    }


    @RequestMapping("/hello")
    @ResponseBody
    public String hello() throws Exception{

        ServiceInstance instance = discoveryClient.getLocalServiceInstance();

        logger.info("/hello, host:{},service_id:{}", instance.getHost(),instance.getServiceId());

        return "hello !";
    }

    @RequestMapping(value = "/hello1", method = RequestMethod.GET)
    @ResponseBody
    public String hello1(@RequestParam String name) {

        logger.info("/hello1");
        return "hello " + name;
    }

    @RequestMapping(value = "/hello2", method = RequestMethod.GET)
    @ResponseBody
    public User hello2(@RequestHeader String name, @RequestHeader Integer age) {

        logger.info("/hello2");
        return new User(name, age);
    }

    @RequestMapping( value = "/hello3", method = RequestMethod.POST)
    @ResponseBody
    public String hello3(@RequestBody User user) {

        logger.info("/hello3");
        return "hello " + user.getName() + ", " + user.getAge();
    }


}
